use crate::cp_heat::Error;
use cmsis_rtos2_rs::{os_kernel_get_tick_count, static_mem::MutexValue};
use proto_bytes::message::MessageRef;
use utils::{bincodec::Decode, log};

#[derive(Debug, Clone, Copy)]
pub struct Status {
    pub bucket1: u32,
    pub bucket2: u32,
    pub update_tick: u32,
}

static BUCKET_INFO: MutexValue<Option<Status>> = MutexValue::uninit(None);

pub unsafe fn init() {
    BUCKET_INFO.init_once("weight info");
}

pub fn status() -> Result<Status, Error> {
    BUCKET_INFO.lock().ok_or(Error::NoRecvWeightStatus)
}

pub fn dispath(msg: MessageRef) {
    if !msg.is_valid_cmd() {
        return;
    }

    let req = msg.into_req();
    let cmd = req.cmd();
    if cmd != crate::cmd::STATUS {
        return;
    }

    #[derive(Debug, Decode)]
    struct _Status {
        _version: u16,
        b1: u32,
        b2: u32,
        _flag: u8,
    }

    let status: _Status = match req.parse_with_decode() {
        Some(v) => v,
        None => {
            log!("parse fail");
            return;
        }
    };

    let current = os_kernel_get_tick_count();

    let mut context = BUCKET_INFO.lock();

    *context = Some(Status {
        bucket1: status.b1,
        bucket2: status.b2,
        update_tick: current,
    })

}
